'use client'

import { useState, useEffect } from 'react'
import { 
  Row, Col, Card, Input, Select, Button, Typography, Pagination, 
  Spin, message, Image, Tag, Space, InputNumber, Breadcrumb 
} from 'antd'
import { 
  SearchOutlined, FilterOutlined, ShoppingCartOutlined, 
  EyeOutlined, HeartOutlined, StarFilled 
} from '@ant-design/icons'
import Link from 'next/link'
import { request } from '@/utils/request'
import { API_ENDPOINTS, PAGINATION, IMAGE_CONFIG } from '@/utils/constants'

const { Title, Text, Paragraph } = Typography
const { Option } = Select
const { Search } = Input

interface Product {
  id: number
  name: string
  description: string
  price: number
  stockQuantity: number
  unit: string
  origin: string
  species: string
  grade: string
  imageUrl: string
  status: string
  categoryName: string
}

interface Category {
  id: number
  name: string
}

interface SearchParams {
  keyword?: string
  categoryId?: number
  minPrice?: number
  maxPrice?: number
  origin?: string
  grade?: string
  sortBy?: string
  sortDirection?: string
  page: number
  size: number
}

export default function ProductsPage() {
  const [products, setProducts] = useState<Product[]>([])
  const [categories, setCategories] = useState<Category[]>([])
  const [loading, setLoading] = useState(false)
  const [total, setTotal] = useState(0)
  const [searchParams, setSearchParams] = useState<SearchParams>({
    page: 0,
    size: PAGINATION.DEFAULT_PAGE_SIZE
  })

  // 加载分类列表
  useEffect(() => {
    loadCategories()
  }, [])

  // 加载产品列表
  useEffect(() => {
    loadProducts()
  }, [searchParams])

  const loadCategories = async () => {
    try {
      const response = await request.get(API_ENDPOINTS.PRODUCTS.CATEGORIES)
      if (response.code === 200) {
        setCategories(response.data)
      }
    } catch (error) {
      console.error('Failed to load categories:', error)
    }
  }

  const loadProducts = async () => {
    setLoading(true)
    try {
      let response
      if (searchParams.keyword || searchParams.categoryId || searchParams.minPrice || searchParams.maxPrice) {
        // 使用搜索接口
        response = await request.post(API_ENDPOINTS.PRODUCTS.SEARCH, searchParams)
      } else {
        // 使用列表接口
        response = await request.get(`${API_ENDPOINTS.PRODUCTS.LIST}?page=${searchParams.page}&size=${searchParams.size}`)
      }
      
      if (response.code === 200) {
        setProducts(response.data.content)
        setTotal(response.data.totalElements)
      }
    } catch (error: any) {
      message.error(error.message || '加载产品失败')
    } finally {
      setLoading(false)
    }
  }

  const handleSearch = (keyword: string) => {
    setSearchParams(prev => ({ ...prev, keyword, page: 0 }))
  }

  const handleFilterChange = (key: string, value: any) => {
    setSearchParams(prev => ({ ...prev, [key]: value, page: 0 }))
  }

  const handlePageChange = (page: number, size?: number) => {
    setSearchParams(prev => ({ ...prev, page: page - 1, size: size || prev.size }))
  }

  const addToCart = async (productId: number, quantity: number = 1) => {
    try {
      const response = await request.post(`${API_ENDPOINTS.CART.ADD}?productId=${productId}&quantity=${quantity}`)
      if (response.code === 200) {
        message.success('添加到购物车成功')
      }
    } catch (error: any) {
      if (error.message.includes('401')) {
        message.error('请先登录')
      } else {
        message.error(error.message || '添加失败')
      }
    }
  }

  return (
    <div style={{ padding: '20px', minHeight: '100vh', background: '#f5f5f5' }}>
      {/* 面包屑导航 */}
      <Breadcrumb style={{ marginBottom: '20px' }}>
        <Breadcrumb.Item><Link href="/">首页</Link></Breadcrumb.Item>
        <Breadcrumb.Item>产品列表</Breadcrumb.Item>
      </Breadcrumb>

      {/* 标题 */}
      <Title level={2} style={{ marginBottom: '30px' }}>产品列表</Title>

      {/* 搜索和筛选 */}
      <Card style={{ marginBottom: '20px' }}>
        <Row gutter={[16, 16]}>
          <Col xs={24} md={8}>
            <Search
              placeholder="搜索产品名称或描述"
              enterButton={<SearchOutlined />}
              size="large"
              onSearch={handleSearch}
            />
          </Col>
          <Col xs={24} md={4}>
            <Select
              placeholder="选择分类"
              style={{ width: '100%' }}
              size="large"
              allowClear
              onChange={(value) => handleFilterChange('categoryId', value)}
            >
              {categories.map(category => (
                <Option key={category.id} value={category.id}>{category.name}</Option>
              ))}
            </Select>
          </Col>
          <Col xs={12} md={3}>
            <InputNumber
              placeholder="最低价格"
              style={{ width: '100%' }}
              size="large"
              min={0}
              onChange={(value) => handleFilterChange('minPrice', value)}
            />
          </Col>
          <Col xs={12} md={3}>
            <InputNumber
              placeholder="最高价格"
              style={{ width: '100%' }}
              size="large"
              min={0}
              onChange={(value) => handleFilterChange('maxPrice', value)}
            />
          </Col>
          <Col xs={24} md={3}>
            <Select
              placeholder="排序方式"
              style={{ width: '100%' }}
              size="large"
              defaultValue="createdAt_desc"
              onChange={(value) => {
                const [sortBy, sortDirection] = value.split('_')
                handleFilterChange('sortBy', sortBy)
                handleFilterChange('sortDirection', sortDirection)
              }}
            >
              <Option value="createdAt_desc">最新上架</Option>
              <Option value="price_asc">价格从低到高</Option>
              <Option value="price_desc">价格从高到低</Option>
              <Option value="name_asc">名称A-Z</Option>
            </Select>
          </Col>
          <Col xs={24} md={3}>
            <Button 
              icon={<FilterOutlined />} 
              size="large" 
              block
              onClick={() => setSearchParams({ page: 0, size: PAGINATION.DEFAULT_PAGE_SIZE })}
            >
              清空筛选
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 产品列表 */}
      <Spin spinning={loading}>
        <Row gutter={[16, 16]}>
          {products.map(product => (
            <Col xs={24} sm={12} md={8} lg={6} key={product.id}>
              <Card
                hoverable
                cover={
                  <div style={{ height: '200px', overflow: 'hidden' }}>
                    <Image
                      alt={product.name}
                      src={product.imageUrl || IMAGE_CONFIG.DEFAULT_PRODUCT}
                      style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                      preview={false}
                    />
                  </div>
                }
                actions={[
                  <Link href={`/products/${product.id}`} key="view">
                    <EyeOutlined /> 查看详情
                  </Link>,
                  <Button 
                    key="cart" 
                    type="text" 
                    icon={<ShoppingCartOutlined />}
                    onClick={() => addToCart(product.id)}
                    disabled={product.stockQuantity === 0}
                  >
                    加入购物车
                  </Button>,
                  <HeartOutlined key="favorite" />
                ]}
              >
                <Card.Meta
                  title={
                    <div>
                      <Link href={`/products/${product.id}`}>
                        <Text strong style={{ fontSize: '16px' }}>{product.name}</Text>
                      </Link>
                      {product.grade && (
                        <Tag color="gold" style={{ marginLeft: '8px' }}>
                          <StarFilled /> {product.grade}
                        </Tag>
                      )}
                    </div>
                  }
                  description={
                    <div>
                      <Paragraph 
                        ellipsis={{ rows: 2 }} 
                        style={{ marginBottom: '10px', color: '#666' }}
                      >
                        {product.description}
                      </Paragraph>
                      <Space direction="vertical" style={{ width: '100%' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                          <Text type="secondary">产地：{product.origin}</Text>
                          <Tag color={product.stockQuantity > 0 ? 'green' : 'red'}>
                            {product.stockQuantity > 0 ? `库存${product.stockQuantity}${product.unit}` : '无库存'}
                          </Tag>
                        </div>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <Text strong style={{ fontSize: '18px', color: '#ff4d4f' }}>
                            ￥{product.price.toFixed(2)}/{product.unit}
                          </Text>
                          <Text type="secondary">{product.categoryName}</Text>
                        </div>
                      </Space>
                    </div>
                  }
                />
              </Card>
            </Col>
          ))}
        </Row>

        {/* 无数据提示 */}
        {!loading && products.length === 0 && (
          <div style={{ textAlign: 'center', padding: '60px 0' }}>
            <Text type="secondary" style={{ fontSize: '16px' }}>
              暂无产品数据
            </Text>
          </div>
        )}
      </Spin>

      {/* 分页 */}
      {total > 0 && (
        <div style={{ textAlign: 'center', marginTop: '30px' }}>
          <Pagination
            current={searchParams.page + 1}
            pageSize={searchParams.size}
            total={total}
            showSizeChanger
            showQuickJumper
            showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`}
            onChange={handlePageChange}
            onShowSizeChange={handlePageChange}
          />
        </div>
      )}
    </div>
  )
}